package com.alogic.ac.loader.aak.xscript;

import com.alogic.ac.AccessAppKey;
import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * 创建一个AAK
 *
 * @since 1.6.12.54 [20191219]
 */
public class AAKNew extends AbstractLogiclet {
    /**
     * 当前节点的上下文id
     */
    protected String cid = "$aak-object";

    protected String $keyId;
    protected String $keyContent;
    protected String $serviceId;
    protected String $verifier;
    protected String $bucket;


    public AAKNew(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        $keyId = PropertiesConstants.getRaw(p, "keyId", "");

        $keyContent = PropertiesConstants.getRaw(p, "keyContent", $keyContent);
        $serviceId = PropertiesConstants.getRaw(p, "serviceId", $serviceId);
        $verifier = PropertiesConstants.getRaw(p, "verifier", $verifier);
        $bucket = PropertiesConstants.getRaw(p, "bucket", $bucket);

        cid = PropertiesConstants.getString(p,"cid", cid,true);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx,
                             ExecuteWatcher watcher) {
        String keyId = PropertiesConstants.transform(ctx,$keyId,"");
        String serviceId = PropertiesConstants.transform(ctx,$serviceId,"");
        String verifier = PropertiesConstants.transform(ctx,$verifier,"");
        String keyContent = PropertiesConstants.transform(ctx,$keyContent,"");
        String bucket = PropertiesConstants.transform(ctx,$bucket,"0");
        if (StringUtils.isNotEmpty(keyId)
                && StringUtils.isNotEmpty(serviceId)
                && StringUtils.isNotEmpty(verifier)
                && StringUtils.isNotEmpty(keyContent)){
            AccessAppKey aak = new MyAAK(keyId,serviceId,verifier,keyContent,bucket);
            ctx.setObject(cid,aak);
        }
    }

    /**
     * 自己的实现
     */
    public static class MyAAK extends AccessAppKey.Default{
        public MyAAK(String id, String serviceId, String verifier, String keyContent,String bucket){
            this.key = id;
            this.appId = serviceId;
            this.verifier = verifier;
            this.keyContent = keyContent;
            this.timeBucket = bucket;
        }
    }
}